﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mimoza.Transport;

namespace Mimoza.AgentLayer
{
    class TimeSynchronizer : BaseObject
    {
        public TimeSynchronizer(Configuration config)
            : base(config)
        {
        }

        void OnServerConnection(Connection conn)
        {
            if (Configuration.Settings.IsTimeSynchronizeFromServer)
            {
                SyncTimeFromServer(conn);
            }
        }

        void SyncTimeFromServer(Connection conn)
        {
            try
            {
                Common.Logger.Log.Info("TimeSynchronizer.SyncTimeFromServer now - '" + DateTime.Now.ToString() + "'...");

                DateTime dateTime = GetDateTimeFormServer(conn);

                SetDateTime(dateTime);

                Common.Logger.Log.Info("TimeSynchronizer.SyncTimeFromServer (synchronized) now - '" + DateTime.Now.ToString() + "'...OK");
            }
            catch (Exception e)
            {
                Common.Logger.Log.Error("TimeSynchronizer.SyncTimeFromServer error - " + e.ToString() + ".");
            }
        }

        DateTime GetDateTimeFormServer(Connection conn)
        {
            Communication.RequestTimeSynch reqTimeSync = new Communication.RequestTimeSynch();

            reqTimeSync.HostId = new Guid(Configuration.Settings.HostId);

            Communication.ReplyTimeSynch replyTimeSync = conn.MakeRequest(reqTimeSync)
                as Communication.ReplyTimeSynch;

            if (replyTimeSync.HostIdTo != reqTimeSync.HostId)
                throw new AgentErrorInServerCommunicationException();

            return replyTimeSync.ServiceDateTime;
        }

        static void SetDateTime(DateTime dateTime)
        {
            Common.Logger.Log.Trace("TimeSynchronizer.SyncTimeFromServer SetTime - " + dateTime.ToString() + ".");

            SystemTime.SetTime(dateTime);
        }

        void RegisterInTransport()
        {
            Communication.RequestTimeSynch.RegisterInTransport();
            Communication.ReplyTimeSynch.RegisterInTransport();
        }
    }
}
